<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2021/5/17
 * Time: 14:34
 */

namespace App\Services\CPC;


use App\Patent;
use App\PatentFee;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use QL\QueryList;

class CPCParseService
{
    public $error_file;

    public function checkHtml()
    {
        $arr = glob(storage_path('gather/fee/*'));
        $ql = QueryList::getInstance();
        $count = 0;
        foreach ($arr as $path) {
            $ql->setHtml(file_get_contents($path));
            $spanId = $ql->find('span:last')->attr('id');
            if(!$spanId){
                unlink($path);
                $patent_sn = trim(basename($path), '.html');
                $this->writeError($patent_sn);
                $count++;
            }
        }
        echo $count;
    }

    public function parseFee()
    {
        $arr = glob(storage_path('gather/fee/*'));
        $count =0;
        foreach ($arr as $path) {
            $patent_sn = trim(basename($path), '.html');
            $data = $this->getFee(file_get_contents($path));
            $this->saveFee($patent_sn,$data);
            $count++;
            echo $patent_sn.'---'.$count."\n";
        }
    }

    protected function saveFee($patent_sn, $data)
    {
        DB::beginTransaction();
        try {
            $patent = Patent::where('patent_sn', $patent_sn)->first();
            if (!$patent) return false;
            PatentFee::where('patent_id', $patent->id)->delete();
            $unpaid = [];
            foreach ($data['unpaid'] as $item) {
                $unpaid[] = array_merge($item, [
                    'state' => 0,
                    'patent_id' => $patent->id,
                    'user_id' => $patent->user_id,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
            }
            PatentFee::insert($unpaid);
            $paid = [];
            foreach ($data['paid'] as $item) {
                $paid[] = array_merge($item, [
                    'state' => 1,
                    'patent_id' => $patent->id,
                    'user_id' => $patent->user_id,
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                ]);
            }
            PatentFee::insert($paid);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::info($patent->patent_sn . '-更新费用失败：' . $exception->getMessage());
        }
    }

    public function parseDetail()
    {

    }

    protected function getFee($html)
    {
        $ql = QueryList::getInstance();
        $ql->setHtml($html);
        $ql = $this->addClass($ql, 'abc111111');
        if (!$ql) return [];
        $data['unpaid'] = $ql->rules([
            'name' => ['td:eq(0) .abc111111', 'text'],
            'amount' => ['td:eq(1) .abc111111', 'text'],
            'last_time' => ['td:eq(2) .abc111111', 'text'],
            'state' => ['td:eq(3) .abc111111', 'text'],
        ])->range('#djfid>table>tr:not(:first)')->queryData();
        $data['paid'] = $ql->rules([
            'name' => ['td:eq(0) .abc111111', 'text'],
            'amount' => ['td:eq(1) .abc111111', 'text'],
            'pay_time' => ['td:eq(2) .abc111111', 'text'],
            'payer' => ['td:eq(3) .abc111111', 'text'],
            'bill_code' => ['td:eq(4) .abc111111', 'text'],
            'bill_number' => ['td:eq(5) .abc111111', 'text'],
        ])->range('#yjfid>table>tr:not(:first)')->queryData();
        return $data;
    }

    protected function addClass(QueryList $ql, $class)
    {
        $spanId = $ql->find('span:last')->attr('id');
        if (!$spanId) return '';
        $ids = $this->parseIds($spanId);
        foreach ($ids as $id) {
            if ($id) {
                $ql->find('#' . $id)->addClass($class);
            }
        }
        return $ql;
    }

    private function parseIds($spanId)
    {
        $b2 = "";
        $b4 = 0;
        $length = strlen($spanId);
        for ($b3 = 0; $b3 < $length; $b3 += 2) {
            if ($b4 > 255) {
                $b4 = 0;
            }
            //hexdec  16进制转10进制
            $b1 = intval(intval(hexdec(substr($spanId, $b3, 2))) ^ $b4++);
            //chr  相当于 js的fromCharCode  将编码转字符
            $b2 .= chr($b1);
        }
        return explode(',', $b2);
    }

    public function writeError($msg, $type = 1)
    {
        $this->error_file = storage_path('gather/err.txt');
        if ($this->error_file) {
            file_put_contents($this->error_file, $msg . "|", FILE_APPEND);
        }
    }
}
